from PyQt4.QtGui import * 
from PyQt4.QtCore import * 

class MapLayerList(QWidget):
    """A widget to hold a QListWidget with a list of layers in the current Map."""
    def __init__(self, map):
        QWidget.__init__(self, None)
        self.vbox_outer = QVBoxLayout()
        self.layer_list_groupbox = QGroupBox("Layers")
        self.vbox = QVBoxLayout()
        self.list = QListWidget()
        self.map = map

        self.buttonhboxcontainer = QWidget()
        self.buttonhbox = QHBoxLayout(self.buttonhboxcontainer)
        self.buttons = {}

        self.buttons["add_layer"] = QPushButton("+")
        self.buttons["del_layer"] = QPushButton("-")

        for key,button in self.buttons.items():
            self.connect(button, SIGNAL("clicked()"), getattr(self,key))
            self.buttonhbox.addWidget(button)
            self.buttonhbox.setAlignment(button, Qt.AlignLeft)
        
        self.vbox.addWidget(self.list)
        self.vbox.addWidget(self.buttonhboxcontainer)

        self.layer_list_groupbox.setLayout(self.vbox)

        self.vbox_outer.addWidget(self.layer_list_groupbox)
        self.setLayout(self.vbox_outer)

        self.initialize_dialog()
        self.initialize_list()

    def add_layer(self):
        # TODO: Dialog to ask for layer tile size.
        self.map.add_layer(32,32)
        self.initialize_list()
        # TODO: Select new layer.

    def del_layer(self):
        self.map.del_layer(self.list.currentRow())
        self.initialize_list()
        # TODO: Select previous layer.

    def initialize_dialog(self):
        self.connect(self.list, SIGNAL("currentRowChanged(int)"), self.row_changed)

    def initialize_list(self):
        """Clear and (re-)initialize list elements."""
        self.list.clear()
        for index,layer in enumerate(self.map.layers):
            item = QListWidgetItem("Layer " + str(index + 1))
            # Create an icon for this item.
            self.list.addItem(item)

        # Set current index to selected tile id.
        self.list.setCurrentRow(self.map.selected_tile_id, QItemSelectionModel.Select)

    def row_changed(self, ev):
        if self.list.currentRow() >= 0:
	        self.map.set_selected_layer(self.list.currentRow())
